package com.imooc.miaosha.service;

import com.imooc.miaosha.dao.MiaoShaUserDao;
import com.imooc.miaosha.domain.MiaoShaUser;
import com.imooc.miaosha.exception.GlobalException;
import com.imooc.miaosha.redis.MiaoShaUserKey;
import com.imooc.miaosha.redis.RedisService;
import com.imooc.miaosha.result.CodeMsg;
import com.imooc.miaosha.util.UUIDUtil;
import com.imooc.miaosha.vo.LoginVo;
import com.imooc.miaosha.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class MiaoShaUserService {

    public static final String COOKIE_NAME_TOKEN = "token";

    @Autowired
    private MiaoShaUserDao miaoShaUserDao;

    @Autowired
    private RedisService redisService;

    public MiaoShaUser getById(long id){
        //先从缓存中取
        MiaoShaUser user = redisService.get(MiaoShaUserKey.idPrefix, "" + id, MiaoShaUser.class);
        if(user != null) return user;

        //缓存中没有，从数据库中取，并且把它添加到缓存中
        user = miaoShaUserDao.getById(id);
        if(user != null) redisService.set(MiaoShaUserKey.idPrefix,"" + id,user);

        return user;
    }

    public boolean updatePassword(long id,String formPass,String token){
        //取出user
        MiaoShaUser user = getById(id);
        //没有这个用户
        if(user == null) throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);

        //修改密码，更新数据库
        user.setPassword(MD5Util.formPassToDBPass(formPass,user.getSalt()));
        miaoShaUserDao.update(user);
        //更新缓存,token-user缓存（登陆用的）这个不能删除，id-user缓存删除
        redisService.set(MiaoShaUserKey.getTokenPrefix,token,user);
        redisService.delete(MiaoShaUserKey.idPrefix,"" + id);

        return true;
    }

    public String login(HttpServletResponse response, LoginVo loginVo){
        if(loginVo == null){
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }

        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        //判断手机号是否存在
        MiaoShaUser user = getById(Long.parseLong(mobile));
        if(user == null){
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }

        //验证密码
        String DBPass = user.getPassword();
        //这里对前端来的密码第二次MD5处理
        String formPassToDBPass = MD5Util.formPassToDBPass(password, user.getSalt());
        if(!formPassToDBPass.equals(DBPass)){
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }

        //生成Cookie
        String token = UUIDUtil.getUUID();
        addCookie(response,user,token);
        return token;
    }

    public MiaoShaUser getByToken(HttpServletResponse response,String token) {
        //老规矩，public方法先判空
        if(StringUtils.isEmpty(token)){
            return null;
        }

        MiaoShaUser user = redisService.get(MiaoShaUserKey.getTokenPrefix, token, MiaoShaUser.class);
        if(user != null){
            //这一步用来每登陆一次，延长有效期，session默认为30min
            addCookie(response,user,token);
        }
        return user;
    }

    private void addCookie(HttpServletResponse response, MiaoShaUser user, String token) {
        redisService.set(MiaoShaUserKey.getTokenPrefix,token,user);
        Cookie cookie = new Cookie(COOKIE_NAME_TOKEN, token);
        cookie.setMaxAge(MiaoShaUserKey.getTokenPrefix.expireSeconds());
        //设置为根目录，则可以在整个应用范围内使用cookie
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
